/*
 * Project Name spring-boot-tools
 * File Name MPMessageEncoder
 * Package Name com.huxiaosu.tools.cmpp.codec
 * Create Time 2024/4/18
 * Create by name：liujie
 */
package com.huxiaosu.tools.cmpp.codec;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import java.util.Arrays;

/**
 * Description
 *
 * @author liujie
 * @date 2024/4/18 23:36
 */
@Slf4j
@Data
public class MPMessageEncoder extends ProtocolEncoderAdapter {

    private String charset;

    public MPMessageEncoder() {
        this.setCharset("UTF-8");
    }

    public MPMessageEncoder(String charset) {
        this.setCharset(charset);
    }

    @Override
    public void encode(IoSession ioSession, Object message, ProtocolEncoderOutput out) throws Exception {
        byte[] bytes = (byte[]) message;
        if (log.isDebugEnabled()) {
            log.debug("<encode message {}>", Arrays.toString(bytes));
        }
        IoBuffer buf = IoBuffer.allocate(bytes.length, false);

        buf.put(bytes);

        buf.flip();
        out.write(buf);
    }

}
